package com.woniuxy01;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 作者
 * @create 2025-09-16 17:01
 */
public class Test04 {

    public static void main(String[] args) throws IOException {
//        List<Student> students = new ArrayList<Student>();
//        students.add(new Student(1,"zs",11));
//        students.add(new Student(2,"ls",12));
//        students.add(new Student(3,"ww",13));
//        saveStudents(students);
        List<Student> students = loadStudents();
        System.out.println(students);
    }

    //文件中存储的数据还原成集合
    public static List<Student> loadStudents() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("students.txt"));
        List<Student> students = new ArrayList<>();
        //读取一行数据，转成学生对象，对象属性赋值，添加到集合
        String line = null;
        while ((line=br.readLine())!=null){
            Student student = new Student();
            //使用-拆分，数组中存储的就是一个个属性值
            String[] properties = line.split("-");
            //String--->int
            student.setId(Integer.parseInt(properties[0]));
            student.setName(properties[1]);
            student.setAge(Integer.parseInt(properties[2]));
            students.add(student);
        }
        return students;
    }

    //集合中的数据保存到文件中
    public static void saveStudents(List<Student> students) throws IOException {
        BufferedWriter bw=new BufferedWriter(new FileWriter("students.txt"));
        for(Student student:students){
            bw.write(student.getId()+"-");
            bw.write(student.getName()+"-");
            bw.write(student.getAge()+"");
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }

}
